const WXAPI = require('../../wxapi/main')
const CONFIG = require('../../config.js')
//获取应用实例
var app = getApp()
Page({
  data: {
    inputShowed: false, // 是否显示搜索框
    inputVal: "", // 搜索框内容
    goods: [],
    loadingMoreHidden: true,
    pageSize: 100,//展示商品数
    balance: 0.00,
    freeze: 0,
    score: 0,
    score_sign_continuous: 0,
    cashlogs: undefined,
    myscore:'',
    mygoods:''
  },
  onShow: function () {
    const _this = this
    // 获取积分
    wx.request({
      // url: "https://www.brvpmusic.com/sign_space/parameter",
      url: 'https://www.brvpmusic.com/integral_space/balance',
      data: {
        'cOpenid': wx.getStorageSync("OpenId"),
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res.data);
        _this.setData({
          'myscore': res.data.body
        })
        // console.log(typeof (a));
        // console.log("a:"+a);
      },
      fail: function (res) {
        console.log('返回失败');
        wx.showToast({
          title: '未签到不能查看',
          icon: 'loading',
          duration: 1500
        });
      }

    });
    const token = wx.getStorageSync('token')
    if (!token) {
      app.goLoginPageTimeOut()
      return
    }
    WXAPI.userAmount(token).then(function (res) {
      if (res.code == 700) {
        wx.showToast({
          title: '当前账户存在异常',
          icon: 'none'
        })
        return
      }
      if (res.code == 2000) {
        app.goLoginPageTimeOut()
        return
      }
      if (res.code == 0) {
        _this.setData({
          balance: res.data.balance.toFixed(2),
          freeze: res.data.freeze.toFixed(2),
          totleConsumed: res.data.totleConsumed.toFixed(2),
          score: res.data.score
        });
      }
    })
    // 读取积分明细
    WXAPI.scoreLogs({
      token: token,
      page: 1,
      pageSize: 50
    }).then(res => {
      if (res.code == 0) {
        _this.setData({
          cashlogs: res.data.result
        })
      }
    })
  },

  // 弹出红包
  onReady() {
    this.showModal()
  },
  showModal() {
    this.setData({
      modalName: 'Image'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  tabClick: function (e) {
    let offset = e.currentTarget.offsetLeft;
    if (offset > 150) {
      offset = offset - 150
    } else {
      offset = 0;
    }
    this.setData({
      activeCategoryId: e.currentTarget.id,
      curPage: 1,
      cateScrollTop: offset
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  //事件处理函数
  swiperchange: function (e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function (e) {
    if (e.currentTarget.dataset.id != 0) {
      wx.navigateTo({
        url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
      })
    }
  },
  bindTypeTap: function (e) {
    this.setData({
      selectCurrent: e.index
    })
  },


  onLoad: function (e) {
    var that = this;
    // 首页商品获取
    wx.request({
      // url: 'http://3s.dkys.org:25333/api/banner/list',
      url: 'https://www.brvpmusic.com/api/products/onecategoryList?oId=11',
      // url: 'https://www.brvpmusic.com/api/products/getList',
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log('首页商品获取成功');
        console.log(res.data)
        that.setData({
          'mygoods': res.data.body,
        })
      },
      fail: function (res) {
        console.log('返回失败');
      }
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene)
      if (scene) {
        wx.setStorageSync('referrer', scene.substring(11))
      }
    }

    /**
     * 示例：
     * 调用接口封装方法
     */
  
    WXAPI.goodsCategory().then(function (res) {
      let categories = [];
      if (res.code == 0) {
        categories = categories.concat(res.data)
      }
      const _n = Math.ceil(categories.length / 2)
      // const _n = Math.ceil(categories.length)
      that.setData({
        categories: categories,
        category_box_width: 150 * _n,
        activeCategoryId: 0,
        curPage: 1
      });
      that.getGoodsList(0);
    })
    WXAPI.goods({
      recommendStatus: 1
    }).then(res => {
      if (res.code === 0) {
        that.setData({
          goodsRecommend: res.data
        })
      }
    })
  },
  onPageScroll(e) {
    let scrollTop = this.data.scrollTop
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  getGoodsList: function (categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    var that = this;
    wx.showLoading({
      "mask": true
    })
    WXAPI.goods({
      categoryId: categoryId,
      nameLike: that.data.inputVal,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    }).then(function (res) {
      wx.hideLoading()
      if (res.code == 404 || res.code == 700) {
        let newData = {
          loadingMoreHidden: false
        }
        if (!append) {
          newData.goods = []
        }
        that.setData(newData);
        return
      }
      let goods = [];
      if (append) {
        goods = that.data.goods
      }
      for (var i = 0; i < res.data.length; i++) {
        goods.push(res.data[i]);
      }
      that.setData({
        loadingMoreHidden: true,
        goods: goods,
      });
    })
  },
  getCoupons: function () {
    var that = this;
    WXAPI.coupons().then(function (res) {
      if (res.code == 0) {
        that.setData({
          coupons: res.data
        });
      }
    })
  },
  onShareAppMessage: function () {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + CONFIG.shareProfile,
      path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  getNotice: function () {
    var that = this;
    WXAPI.noticeList({ pageSize: 5 }).then(function (res) {
      if (res.code == 0) {
        that.setData({
          noticeList: res.data
        });
      }
    })
  },
  toSearch: function () {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  onReachBottom: function () {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.getGoodsList(this.data.activeCategoryId, true)
  },
  onPullDownRefresh: function () {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId)
    wx.stopPullDownRefresh()
  },

  
  // 页面跳转
  goExcharge: function () {
    wx.navigateTo({
      url: "/pages/score-excharge/index"
    })
  },
  goSign: function () {
    wx.navigateTo({
      url: "/pages/sign/sign_in"
    })
  },
  goScore: function () {
    wx.navigateTo({
      url: "/pages/score/index"
    })
  },
})